import React, { useState, useEffect } from 'react';
import { DatePicker, Checkbox } from '@block/plug';
import './CompleteTimePicker.scss';
import { datejs } from '@block/utils';

/**
 * 业务方反馈可编辑表格-预计完成时间
 * 时间组件
 */
interface Props extends DefaultToEditItem {
  onChange?: (key: string, val) => void;
  mode?: Mode;
  planCompleteTime: number;
  rectifyCompletion: boolean;
}
const CompleteTimePicker = (props: Props) => {
  const { onChange, mode, planCompleteTime, rectifyCompletion } = props;

  const [time, setTime] = useState(planCompleteTime);
  const [checked, setChecked] = useState(rectifyCompletion);
  /** Checkbox点击 */
  const handleChecked = (e) => {
    const { checked: changeChecked } = e?.target ?? {};
    setChecked(changeChecked);
    onChange?.('rectifyCompletion', changeChecked);
  };
  /** DatePicker点击 */
  const handleTime = (val: number) => {
    setTime(val);
    onChange?.('planCompleteTime', val);
  };

  useEffect(() => {
    setTime(planCompleteTime);
  }, [planCompleteTime]);
  useEffect(() => {
    setChecked(rectifyCompletion);
  }, [rectifyCompletion]);

  const renderView = () => {
    if (rectifyCompletion) return '已完成';
    if (planCompleteTime) return datejs(planCompleteTime).format('YYYY-MM-DD');
    return '-';
  };

  return (
    <span className="complete-time-picker">
      {mode === 'edit' ? (
        <>
          <DatePicker
            className="complete-time-picker-date-picker"
            value={time}
            valueFormat="timestamp"
            disabled={checked}
            placeholder="选择日期"
            onChange={handleTime}
          />
          <Checkbox checked={checked} onChange={handleChecked}>
            已完成
          </Checkbox>
        </>
      ) : (
        renderView()
      )}
    </span>
  );
};
export default CompleteTimePicker;
